package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpService empService;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Clazz> listClazz(ClazzDTO clazzDTO) {
        Page<Clazz> clazzPage = Page.of(clazzDTO.getPage(), clazzDTO.getPageSize());
        clazzPage.addOrder(OrderItem.desc("update_time"));
        lambdaQuery()
                .like(clazzDTO.getName() != null && !clazzDTO.getName().isEmpty(), Clazz::getName, clazzDTO.getName())
                .between(clazzDTO.getBegin() != null && clazzDTO.getEnd() != null, Clazz::getEndDate, clazzDTO.getBegin(), clazzDTO.getEnd())
                .page(clazzPage);
        //查询到班级结果集后，需要通过master_id来获取到员工表中的班主任数据集
        List<Clazz> clazzList = clazzPage.getRecords();
        List<Integer> masterIds = clazzList.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());
        if(!masterIds.isEmpty()){
            Map<Integer, String> empMap = empService.listByIds(masterIds).stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
            clazzList.forEach(clazz -> {clazz.setMasterName(empMap.getOrDefault(clazz.getMasterId(), "null"));});
        }
        clazzPage.getRecords().forEach(clazz -> {
            if (clazz.getBeginDate() != null && clazz.getBeginDate().isAfter(LocalDate.now())) {
                clazz.setStatus("未开班");
            }
            else if (clazz.getEndDate() !=null && clazz.getEndDate().isBefore(LocalDate.now())){
                clazz.setStatus("已结课");
            }
            else {
                clazz.setStatus("已开课");
            }
        });
        return new PageResult<>(clazzPage.getTotal(), clazzPage.getRecords());
    }

    @Override
    public void saveClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        save(clazz);
    }

    @Override
    public Clazz getByIdClazz(Integer id) {
        Clazz clazz = getById(id);
        return clazz;
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        lambdaUpdate()
            .eq(Clazz::getId, clazz.getId())
            .set(Clazz::getName, clazz.getName())
            .set(Clazz::getRoom, clazz.getRoom())
            .set(Clazz::getBeginDate, clazz.getBeginDate())
            .set(Clazz::getUpdateTime, clazz.getUpdateTime())
            .set(Clazz::getEndDate, clazz.getEndDate())
            .set(Clazz::getMasterId, clazz.getMasterId())
            .set(Clazz::getSubject, clazz.getSubject())
            .update();
    }

    @Override
    public void deleteClazz(Integer id) {
        long count = studentMapper.selectCount((new LambdaQueryWrapper<Student>().eq(Student::getClazzId, id)));
        if(count > 0){
            throw new RuntimeException("该班级被学员所关联，不允许删除");
        }
        removeById(id);
    }

    @Override
    public List<Clazz> Clazzlist() {
        return list();
    }
}
